package edu.cuit.avatar.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/17 13:59
 */
public class CountDownLatchTest {
    private static final int MAX_WORK_DURATION = 5000;  // 最大工作时间
    private static final int MIN_WORK_DURATION = 1000;  // 最小工作时间

    // 产生随机的工作时间
    private static long getRandomWorkDuration(long min, long max) {
        return (long) (Math.random() * (max - min) + min);
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);   // 创建倒计时闩并指定倒计时次数为3
        Worker w1 = new Worker("Peppa", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));
        Worker w2 = new Worker("Emily", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));
        Worker w3 = new Worker("Pedro", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));

        var executor = Executors.newFixedThreadPool(3);
        executor.execute(new WorkTask(w1, latch));
        executor.execute(new WorkTask(w2, latch));
        executor.execute(new WorkTask(w3, latch));

        try {
            latch.await();  // 等待倒计时闩减到0
            System.out.println("All jobs have been finished!");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static class Worker{
        private String name;        // 名字
        private long workDuration;  // 工作持续时间

        public Worker(String name, long workDuration) {
            this.name = name;
            this.workDuration = workDuration;
        }

        public void doWork(){
            System.out.println(name + " begins to work...");
            try {
                Thread.sleep(workDuration);// 用休眠模拟工作执行的时间
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(name + " has finished the job...");
        }
    }

    private static class WorkTask implements Runnable{
        private Worker worker;
        private CountDownLatch cdl;

        public WorkTask(Worker worker, CountDownLatch cdl) {
            this.worker = worker;
            this.cdl = cdl;
        }

        @Override
        public void run() {
            worker.doWork();        // 让工人开始工作
            cdl.countDown(); //倒计时门闩减一
        }
    }
}
